package com.think.teaching.controller;

import com.think.common.model.Result;
import com.think.common.model.ResultCode;
import com.think.common.utils.Common;
import com.think.common.utils.JSonUtil;
import com.think.common.utils.NetUtils;
import com.think.teaching.model.Class;
import com.think.teaching.model.College;
import com.think.teaching.model.Major;
import com.think.teaching.model.StudentImportBean;
import com.think.teaching.model.StudentInfo;
import com.think.teaching.model.User;
import com.think.teaching.service.impl.ClassServiceImpl;
import com.think.teaching.service.impl.CollegeServiceImpl;
import com.think.teaching.service.impl.MajorServiceImpl;
import com.think.teaching.service.impl.StudentInfoServiceImpl;
import com.think.teaching.service.impl.UserServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 学生详细信息 前端控制器
 * </p>
 *
 * @author think
 * @since 2020-08-12
 */
@RestController
@RequestMapping("/v1")
@ResponseBody
@Api(tags = "学生信息管理接口")
public class StudentInfoController {
	@Autowired
	private StudentInfoServiceImpl studentInfoServiceImpl;
	@Autowired
	private ClassServiceImpl classServiceImpl;
	@Autowired
	private MajorServiceImpl majorServiceImpl;
	@Autowired
	private CollegeServiceImpl collegeServiceImpl;

	@Autowired
	private UserServiceImpl userServiceImpl;
//	/**
//	 * 青海大学
//	 */
//	private static final String PREFIX = "qu";
//	/**
//	 * 陕西师范大学
//	 */
//	private static final String PREFIX = "snnu";
	/**
	 * 陕西师范大学
	 */
	@Value("${platform.userPrefix}")
	private String PREFIX;

	@Value("${user.server.url}")
	public String userServerUrl;

	@ApiOperation("添加新的学生信息")
	@PostMapping("admin/studentInfo")
	public Result AddNewStudentInf(@RequestBody() Map<String, Object> data) {
		String name = data.get("studentName").toString();
		String studentId = data.get("studentId").toString();
		Integer classId = Integer.parseInt(data.get("classId").toString());
		String parm = "name=" + PREFIX + studentId + "&nickname=" + name + "&access_token="
				+ UserController.getCurrentToken();
		String res = "";
		try {
			res = NetUtils.doPost(userServerUrl + "/v1/admin/user", parm, null);
			Map<String, Object> resp = JSonUtil.fromJson(res, Map.class);
			resp = (Map<String, Object>) resp.get("data");
			Integer userId = Integer.parseInt(resp.get("id").toString());
			StudentInfo studentInfo = new StudentInfo();
			studentInfo.setClassId(classId);
			studentInfo.setUserId(userId);
			studentInfo.setTrueName(name);
			studentInfo.setStudentId(studentId);
			studentInfo.setState(1);
			studentInfo.setCreatedBy(Common.GetCurrentAuthor().getUserId());
			studentInfo.setUpdatedBy(Common.GetCurrentAuthor().getUserId());
			if (studentInfoServiceImpl.save(studentInfo)) {
				return Result.success(studentInfo);
			} else {
				return Result.failure(ResultCode.SYSTEM_DATABASE_ERROR);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			return Result.failure(ResultCode.SYSTEM_INNER_ERROR, e.getMessage());
		}
	}

	@ApiOperation("导入新的学生信息")
	@PostMapping("admin/studentInfo/import")
	public Result ImportStudentInfo(@RequestBody StudentImportBean data) {

		Integer classId = data.getClassId();
		List<StudentInfo> result = new ArrayList<StudentInfo>();
		for (int i = 0; i < data.getDatas().size(); i++) {
			Map<String, Object> map = data.getDatas().get(i);
			String name = map.get("studentName").toString();
			String studentId = map.get("studentId").toString();
			if (studentId.length() == 0 || studentId.length() == 0)
				continue;
			String parm = "name=" + PREFIX + studentId + "&nickname=" + name + "&access_token="
					+ UserController.getCurrentToken();
			String res = "";
			try {
				res = NetUtils.doPost(userServerUrl + "/v1/admin/user", parm, null);
				System.out.println(res);
				Map<String, Object> resp = JSonUtil.fromJson(res, Map.class);
				resp = (Map<String, Object>) resp.get("data");
				Integer userId = Integer.parseInt(resp.get("id").toString());
				if (studentInfoServiceImpl.GetStudentInfoByUserId(userId) != null) {
					continue;
				}
				StudentInfo studentInfo = new StudentInfo();
				studentInfo.setClassId(classId);
				studentInfo.setUserId(userId);
				studentInfo.setTrueName(name);
				studentInfo.setStudentId(studentId);
				studentInfo.setState(1);
				studentInfo.setCreatedBy(Common.GetCurrentAuthor().getUserId());
				studentInfo.setUpdatedBy(Common.GetCurrentAuthor().getUserId());
				if (studentInfoServiceImpl.save(studentInfo)) {
					result.add(studentInfo);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}

		return Result.success(result);

	}

	@ApiOperation("更新学生信息")
	@RequestMapping(value = "admin/studentInfo", method = RequestMethod.PUT)
	public Result UpdateStudentInf(@RequestBody() StudentInfo data) {
		Result result = data.CheckObjectComplete();
		if (result.getCode() == ResultCode.SUCCESS.code()) {
			StudentInfo studentInfo = studentInfoServiceImpl.UpdateStudentInfo(data);
			if (studentInfo == null) {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			} else {
				result = Result.success(studentInfo);
			}
		}
		return result;
	}

	@ApiOperation("删除学生信息")
	@RequestMapping(value = "admin/studentInfo/del/{id}", method = RequestMethod.POST)
	public Result DeleteStudentInf(@PathVariable("id") Integer id) {
		Result result = Result.success();
		if (studentInfoServiceImpl.getById(id) == null) {
			result = Result.failure(ResultCode.STUDENT_NOT_EXIST);
		} else {
			if (!studentInfoServiceImpl.DeleteObjectById(id)) {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}
		}
		return result;
	}

	@ApiOperation("获取学生信息详情")
	@RequestMapping(value = "user/studentInfo", method = RequestMethod.GET)
	public Result GetStudentInfo() {
		StudentInfo studentInfo = studentInfoServiceImpl.GetStudentInfoByUserId(Common.GetCurrentAuthor().getUserId());
		if (studentInfo != null) {
			Map<String, Object> result = new HashedMap<String, Object>();
			result.put("truename", studentInfo.getTrueName());
			result.put("studentId", studentInfo.getStudentId());
			result.put("state", studentInfo.getState());
			Class class1 = classServiceImpl.getById(studentInfo.getClassId());
			Major major = null;
			if (class1 != null)
				major = majorServiceImpl.getById(class1.getMajor());
			College college = null;
			if (major != null)
				college = collegeServiceImpl.getById(major.getCollege());
			if (class1 != null)
				result.put("class", new HashedMap<String, Object>() {
					{
						put("id", class1.getId());
						put("name", class1.getClassIndex());
					}
				});
			if (major != null) {
				Integer mid = major.getId();
				String mname = major.getMajorName();
				result.put("major", new HashedMap<String, Object>() {
					{
						put("id", mid);
						put("name", mname);
					}
				});
			}
			if (college != null) {
				Integer cid = college.getId();
				String cname = college.getCollegeName();
				result.put("college", new HashedMap<String, Object>() {
					{
						put("id", cid);
						put("name", cname);
					}
				});
			}
			return Result.success(result);// (ResultCode.STUDENT_ALREADY_EXIST);
		} else {
			//如果无该学生信息 返回默认的用户信息
			User user = userServiceImpl.getById(Common.GetCurrentAuthor().getUserId());
			Map<String, Object> result = new HashedMap<String, Object>();
			result.put("truename", user.getNickname());
			result.put("studentId", -1);
			result.put("class", new HashedMap<String, Object>() {
				{
					put("id", -1);
					put("name", "");
				}
			});
			result.put("major", new HashedMap<String, Object>() {
				{
					put("id", -1);
					put("name", "");
				}
			});
			result.put("college", new HashedMap<String, Object>() {
				{
					put("id", -1);
					put("name", "");
				}
			});
			return Result.success(result);// (ResultCode.STUDENT_ALREADY_EXIST);
		}
	}

	@ApiOperation("管理员修改学生信息状态")
	@RequestMapping(value = "admin/studentInfo/update/{id}/{state}", method = RequestMethod.POST)
	public Result UpdateStudentInfoState(@PathVariable("id") Integer id, @PathVariable("state") Integer state) {
		StudentInfo info = studentInfoServiceImpl.GetStudentInfo(id);
		Result result;
		if (info != null) {
			result = Result.success(info);
		} else {
			try {
				info = studentInfoServiceImpl.SetStudentState(id, state);
				result = Result.success(info);// (ResultCode.STUDENT_NOT_EXIST);
			} catch (Exception e) {
				// TODO: handle exception
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR);
			}

		}
		return result;
	}

	@ApiOperation("用户搜索学生信息")
	@RequestMapping(value = "user/studentInfo/search", method = RequestMethod.GET)
	public Result UserSearchStudentInfo(@RequestParam("key") Integer key) {
		return Result.failure(ResultCode.INTERFACE_UNIMPLEMENTED);
	}

	@ApiOperation("管理员搜索学生信息")
	@RequestMapping(value = "admin/studentInfo/search", method = RequestMethod.GET)
	public Result AdminSearchStudentInfo(@RequestParam("key") Integer key) {
		return Result.failure(ResultCode.INTERFACE_UNIMPLEMENTED);
	}

	@ApiOperation("管理员搜索学生信息列表")
	@RequestMapping(value = "admin/studentInfos/{page}/{count}", method = RequestMethod.GET)
	public Result AdminListStudentInfo(@PathVariable("page") Integer page, @PathVariable("count") Integer count,
			@RequestParam(required = false, defaultValue = "-1") Integer id,
			@RequestParam(required = false, defaultValue = "-1") Integer college,
			@RequestParam(required = false, defaultValue = "-1") Integer school,
			@RequestParam(required = false, defaultValue = "-1") Integer major) {
		return Result.success(studentInfoServiceImpl.ListStudentInfo(page, count, 0, id, major, college, school));
	}

	@ApiOperation("用户搜索学生信息列表")
	@RequestMapping(value = "user/studentInfos/{page}/{count}", method = RequestMethod.GET)
	public Result UserListStudentInfo(@PathVariable("page") Integer page, @PathVariable("count") Integer count,
			@RequestParam(required = false, defaultValue = "-1") Integer id,
			@RequestParam(required = false, defaultValue = "-1") Integer college,
			@RequestParam(required = false, defaultValue = "-1") Integer school,
			@RequestParam(required = false, defaultValue = "-1") Integer major) {
		return Result.success(studentInfoServiceImpl.ListStudentInfo(page, count, 1, id, major, college, school));
	}
}
